<template>
  <treeselect
    v-if="areaOptions"
    :options="areaOptions"
    :load-options="loadAreaOptions"
    placeholder="选择所属行政区划"
    v-model="v"
  />
</template>

<script>
import {listAreaByParId} from "@/api/system/area";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "AreaSelect",
  components: { Treeselect },
  model: {
    prop: "value",
    event: "update"
  },
  props: {
    parentId: String,
    value: String
  },
  data() {
    return {
      // 行政区划选项
      areaOptions: null,
      trim0V:null
    }
  },
  computed: {
    v: {
      get() {
        return this.value
      },
      set(newV) {
        this.$emit('update', newV)
      },
    },
  },
  watch: {
    v: {
      immediate: true,
      handler() {
        this.loadAreaRootOptions()
      },
    }
  },
  methods: {
    trimmed0(v) {
      if(!v) return v
      for (let i = v.length-1; ; i--) {
        if (v.charAt(i) !== '0') {
          return v.substr(0, i+1)
        }
      }
      return ''
    },
    loadAreaRootOptions() {
      if (this.areaOptions) {
        if (this.v) {
          this.trim0V = this.trimmed0(this.v);
          this.recursiveLoadCurrentNode(this.areaOptions)
        }
      }else {
        listAreaByParId(this.parentId? this.parentId:"-1").then(res=> {
          this.areaOptions = res.data.map(d=> {
            return {label: d.name, children: d.remark ==='Town'?undefined:null, ...d}
          })
          if (this.v) {
            this.trim0V = this.trimmed0(this.v);
            this.recursiveLoadCurrentNode(this.areaOptions)
          }
        });
      }
    },
    recursiveLoadCurrentNode(nodes = []) {
      nodes.forEach(d=> {
        if(d.id === this.v) return
        if (this.trim0V.startsWith(this.trimmed0(d.id))) {
          if (!d.children) {
            listAreaByParId(d.id).then(res=> {
              d.children = res.data.map(d=> {
                return {label: d.name, children: d.remark ==='Town'?undefined:null, ...d}
              })
              this.recursiveLoadCurrentNode(d.children)
            });
          }else {
            this.recursiveLoadCurrentNode(d.children)
          }
        }
      })
    },
    loadAreaOptions(context) {
      const { parentNode, callback } = context
      listAreaByParId(parentNode.id).then(res=> {
        parentNode.children = res.data.map(d=> {
          return {label: d.name, children: d.remark ==='Town'?undefined:null, ...d}
        });
        callback()
      }).catch(error=> {
        callback(new Error(error))
      })
    },
  }
}
</script>

<style scoped>

</style>
